<?php

namespace mpend\modules\user\models;

use Yii;
use common\helpers\Url;
use common\models\user\UserConnect;

class ProfileSearch extends \common\models\BaseUser {

    public $connect_id;
    private $_gender = 0;

    /**
     * 获取用户第三方绑定信息
     * @inheritdoc
     */
    public function getConnect() {
        return $this->hasOne(UserConnect::class, ['user_id' => 'id']);
    }

    public function getGender() {
        return ($this->meta && $this->meta->gender) ? $this->meta->gender : $this->_gender;
    }

    public function setGender($gender) {
        $this->_gender = $gender;
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ActiveDataProvider
     */
    public function searchOne() {
        $query = static::find();
        if ($this->connect_id) {
            $query->alias('t');
            $query->joinWith('connect c');
            $query->andWhere([
                'c.id' => $this->connect_id,
            ]);
            $query->andFilterWhere([
                't.id' => $this->id,
            ]);
        } else {
            $query->andWhere([
                'id' => $this->id,
            ]);
        }
        return $query->one();
    }

    public function fields() {
        if (!$this->nickname && $this->connect) {
            $data = $this->connect->getAuthData();
            if ($data) {
                $this->nickname = $data['nickname'];
                $this->avatar = $data['avatar'];
                $this->setGender($data['gender']);
            }
        }
        \yii\helpers\HtmlPurifier::class;
        return [
            'id',
            'nickname',
            'avatar' => function() {
                return Url::attach($this->avatar);
            },
            'gender' => function() {
                return $this->meta ? $this->meta->gender : 0;
            },
        ];
    }

}
